package cn.daniellee.qunrobot.component;

import cn.daniellee.qunrobot.KQClient;
import com.mumu.listenner.KQMSGAdapter;
import com.mumu.msg.RE_MSG_Group;
import com.mumu.webclient.KQWebClient;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class QQAdapter extends KQMSGAdapter {

	private KQWebClient kqWebClient;

	public QQAdapter(KQWebClient kqWebClient) {
		this.kqWebClient = kqWebClient;
	}

	@Override
	public void RE_MSG_Group(RE_MSG_Group msg) {
		super.RE_MSG_Group(msg);
		if (KQClient.config.getProperty("qun-number", "5728290").equals(msg.getFromGroup())) {
			String message = msg.getMsg();
			String regPrefix = KQClient.config.getProperty("reg-prefix", "注册玩家：");
			if (message.startsWith(regPrefix)) {
				String name = message.replace(regPrefix, "").trim();
				Pattern pattern = Pattern.compile(KQClient.config.getProperty("name-pattern", "[a-zA-Z0-9_\\\\u4e00-\\\\u9fa5]{3,16}"));
				if (pattern.matcher(name).matches()) {
					BufferedReader reader = null;
					BufferedWriter writer = null;
					try {
						Map<String, String> nameMap = new HashMap<>();
						Map<String, String> qqMap = new HashMap<>();
						reader = new BufferedReader(new InputStreamReader(new FileInputStream(KQClient.listFile), "UTF-8"));
						String temp;
						while ((temp = reader.readLine()) != null) {
							String[] split = temp.split(":");
							nameMap.put(split[0], split[1]);
							qqMap.put(split[1], split[0]);
						}
						if (nameMap.containsKey(name)) {
							kqWebClient.sendGroupMSG(msg.getFromQQ(), msg.getFromGroup(), KQClient.config.getProperty("already-reg", " 用户名已被QQ：%qq%注册，无需再次注册").replace("%qq%", nameMap.get(name)), true);
						} else if (qqMap.containsKey(msg.getFromQQ())) {
							kqWebClient.sendGroupMSG(msg.getFromQQ(), msg.getFromGroup(), KQClient.config.getProperty("already-use", " 您的QQ已注册：%name%，无法再次注册").replace("%name%", qqMap.get(msg.getFromQQ())), true);
						} else {
							writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(KQClient.listFile, true), "UTF-8"));
							writer.write(name + ":" + msg.getFromQQ() + "\n");
							writer.flush();
							kqWebClient.sendGroupMSG(msg.getFromQQ(), msg.getFromGroup(), KQClient.config.getProperty("reg-success", " QQ号【%qq%】玩家名【%name%】注册成功").replace("%qq%", msg.getFromQQ()).replace("%name%", name), true);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (reader != null) {
							try {
								reader.close();
							} catch (IOException ignored) { }
						}
						if (writer != null) {
							try {
								writer.close();
							} catch (IOException ignored) { }
						}
					}
				} else {
					kqWebClient.sendGroupMSG(msg.getFromQQ(), msg.getFromGroup(), KQClient.config.getProperty("invalid-name", " 玩家名不符合规则（3-16个字母|数字|中文）"), true);
				}
			}
		}
	}

}
